package com.xzh.common.valid;

import lombok.var;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;

/**
 * @Author: zhiHong
 * @CreateTime: 2024-01-27 15:18
 * @Description: 自定义校验器
 */
public class EnumConstraintValidator implements ConstraintValidator<EnumValidate, Integer> {
    // 定义一个集合，用于收集EnumValidate传入的values
    private final HashSet<Integer> vs = new HashSet<>();
    @Override
    public void initialize(EnumValidate constraintAnnotation) {
        int[] values = constraintAnnotation.values();
        for(int value : values) {
            vs.add(value);
        }
    }

    /**
     *
     * @param value object to validate
     * @param context context in which the constraint is evaluated
     *
     * @return true: 验证成功，false: 验证失败
     */
    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        return vs.contains(value);
    }
}
